#include<stdio.h>
#include<stdlib.h>
#include<sys/stat.h>
#include<unistd.h>
#include<linux/stat.h>
#include<string.h>

#define FIFO "publicfifo"
#define FIFO1 "privatefilo1"
#define FIFO2 "privatefifo2"

int main(int argc,char *argv[])
{
    FILE *fp;
    FILE *fp1;
    FILE *fp2;
    pid_t pid;
    char readbuf[100];
    char writebuf[100];
    //创建publicfifo
    if((fp=fopen(FIFO,"r"))==NULL)
	{
		umask(0);
		mknod(FIFO,S_IFIFO|0666,0);
	}
	else
		fclose(fp);
    //创建privatefifo1
    if((fp1=fopen(FIFO1,"w"))==NULL)
    {
        umask(0);
        mknod(FIFO1,S_IFIFO|0666,0);
    }
    else 
        fclose(fp1);
    //创建privatefifo2
    if((fp2=fopen(FIFO2,"w"))==NULL)
    {
        umask(0);
        mknod(FIFO2,S_IFIFO|0666,0);
    }
    else
        fclose(fp2);
    
    while(1)
    {
        if((fp=fopen(FIFO,"r"))==NULL)
        {
            printf("open FIFO failed\n");
            exit(1);
        }
        if(fgets(readbuf,sizeof(readbuf),fp)!=NULL)
        {
            printf("the string from public is %s\n",readbuf);
            fclose(fp);
            if(readbuf[0]=='1')
            {
                if((fp1=fopen(FIFO1,"w"))==NULL)
                {
                    printf("open FIFO1 failed.\n");
                    exit(1);
                }
                if(fputs("client1 received",fp1)==EOF)
                {
                    printf("write to privatefifo1 failed.\n");
                    exit(1);
                }
                fclose(fp1);
            }
            else if(readbuf[0]=='2')
            {
                if((fp2=fopen(FIFO2,"w"))==NULL)
                {
                    printf("open FIFO2 failed.\n");
                    exit(1);
                }
                if(fputs("client2 received",fp2)==EOF)
                {
                    printf("write to privatefifo2 failed.\n");
                    exit(1);
                }
                fclose(fp2);
            }
        }
        else
        {
            if(ferror(fp))
            {
                printf("read FIFO failed\n");
                exit(1);
            }
        }
        
    }    
}
